package com.shyroke.daydayzhuansvc.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuanapi.dto.*;
import com.shyroke.daydayzhuanapi.entity.ProjectEntity;
import com.shyroke.daydayzhuanapi.entity.QProjectEntity;
import com.shyroke.daydayzhuanapi.entity.VersionEntity;
import com.shyroke.daydayzhuanapi.mapper.AppMapper;
import com.shyroke.daydayzhuanapi.mapper.ProjectMapper;
import com.shyroke.daydayzhuandao.respository.ProjectRepository;
import com.shyroke.daydayzhuandao.respository.VersionRepository;
import com.shyroke.daydayzhuansvc.service.IProjectService;
import com.shyroke.daydayzhuansvc.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ProjectApiService {
    
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private OSSService ossService;
    @Autowired
    private AppService appService;
    @Autowired
    private AppMapper appMapper;
    @Autowired
    private VersionRepository versionRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    public AppApiModel getIndexData() {
        AppIndexDto data = new AppIndexDto();
        List<ProjectCommentDto> topAllArticles = projectService.getCommentProjectList();
        if(CollUtil.isNotEmpty(topAllArticles)) {
            topAllArticles.stream().forEach(dto -> {
                dto.setDetailUrl("https://www.daydayzhuan.com/article/"+ dto.getId()+"?channel=APP");
                dto.setCover(ossService.getImgUrl(dto.getCover()));
            });
            data.setTopAllArticles(topAllArticles);
            data.setTopArticles(topAllArticles.size()>=5?topAllArticles.subList(0,5):topAllArticles);
        }

//        ProjectCommentDto advert = new ProjectCommentDto();
//        advert.setTitle("龙戒打金搬砖 微信备案 正规可靠");
//        advert.setIsToday("0");
//        advert.setShowCreateTime("09-18");
//        advert.setCreateTime(DateUtil.parse("2023-09-18 19:00:00", "yyyy-MM-dd HH:mm:ss"));
//        advert.setId(0);
//        advert.setCover("");
//        advert.setShowLabel("龙戒打金搬砖");
//        advert.setDetailUrl("https://www.daydayzhuan.com/go");

//        ProjectCommentDto advert2 = new ProjectCommentDto();
//        advert2.setTitle("最新蓝海项目，每日佣金2k起");
//        advert2.setIsToday("0");
//        advert2.setShowCreateTime("10-06");
//        advert2.setCreateTime(DateUtil.parse("2023-10-06 19:45:00", "yyyy-MM-dd HH:mm:ss"));
//        advert2.setId(-1);
//        advert2.setCover("");
//        advert2.setShowLabel("广告");
//        advert2.setDetailUrl("https://docs.qq.com/doc/p/02e18b7dde77e448a9a9dbbeeb5f04c580caced2");

//        List<ProjectCommentDto> topArticles = new ArrayList<>(data.getTopArticles());
////        topArticles.add(1, advert);
//        topArticles.add(2, advert2);
//        data.setTopArticles(topArticles);

//        List<ProjectCommentDto> topAllArticles1 = new ArrayList<>(data.getTopAllArticles());
////        topAllArticles1.add(1, advert);
//        topAllArticles1.add(2, advert2);
//        data.setTopAllArticles(topAllArticles1);

        data.setNewArticles(this.getNewsArticles(1, 10));
        data.setTopApps(this.getTopApps());
        data.setAbout(this.getAbout());
        data.setAppVersion(this.getAppVersion());
        data.setDownUrl("https://www.daydayzhuan.com/goDownload");
        return AppApiModel.builder().Data(data).build();
    }

    private String getAppVersion() {
        Object obj = redisTemplate.opsForValue().get(RedisKeyPrefix.APP_VERSION);
        if(obj == null) {
            VersionEntity e = versionRepository.findById(1).orElse(null);
            if (e == null) {
                return null;
            }
            redisTemplate.opsForValue().set(RedisKeyPrefix.APP_VERSION, e.getVersion());
            return e.getVersion();
        }else {
            return obj.toString();
        }
    }

    private AppAboutDto getAbout() {
        AppAboutDto about = new AppAboutDto();
        about.setSiteUrl("https://www.daydayzhuan.com");
        about.setOwnerContact("http://wpa.qq.com/msgrd?v=3&uin=865386512&site=qq&menu=yes");
        about.setQqGroup1("https://qm.qq.com/cgi-bin/qm/qr?k=46DZT7_a4phsOKWvHU-jkh7jS3delj-v&jump_from=webapi&authKey=+qi/O4IqZkRCAI9Tv2KsO5u/7/TLh+eX/cRLYiZ79w03zmtoeGQLd03yOIooelha");
        about.setQqGroup2("https://qm.qq.com/cgi-bin/qm/qr?k=1tlEyOFZ17yplXEJUBGc4q9LqhixPCRV&jump_from=webapi&authKey=v+UxRm2wjJmn3lJFwUKng8zsU3joLOSJ/q+5SdpwQOmxbO6CzA7xENIBBwMj4ngO");
        about.setWxGroup("微信号：shyroke，备注：线报，拉你进群");
        about.setTouGaoUrl("https://wj.qq.com/s2/12918919/ccf5/");
        about.setMemo("这个家伙很懒，什么也没有留下~~");
        about.setLogo("https://daydayzhuan.oss-cn-shenzhen.aliyuncs.com/img/cover/zm.jpg");
        return about;
    }

    private List<TopAppDto> getTopApps() {
        Object obj = redisTemplate.opsForValue().get(RedisKeyPrefix.TOP_APP);
        if(obj == null) {
            List<AppDto> apps = appService.findByTop(6, false);
            List<TopAppDto> dtos = apps.stream().map(appMapper::dtoToAppDto).collect(Collectors.toList());
            redisTemplate.opsForValue().set(RedisKeyPrefix.TOP_APP, dtos);
            redisTemplate.expire(RedisKeyPrefix.TOP_APP,1, TimeUnit.DAYS);
            return dtos;
        }else {
            return (List<TopAppDto>)obj;
        }
    }

    public List<ProjectAppDto> getNewsArticles(int page, int limit) {
        QProjectEntity qProjectEntity = QProjectEntity.projectEntity;
        JPAQuery<ProjectEntity> query = factory.selectFrom(qProjectEntity)
                .where(qProjectEntity.offline.eq("0"),qProjectEntity.isHomePage.eq("1"))
                .offset(PageRequest.of(page - 1, limit).getOffset()).limit(limit)
                .orderBy(qProjectEntity.createTime.desc());

        List<ProjectEntity> list = query.fetch();
        list.stream().forEach(project->{
            boolean today = CommonUtil.isSameDate(new Date(),project.getCreateTime());
            project.setIsToday(today == true ? "1":"0");
            project.setShowCreateTime(CommonUtil.getDateByFormat(project.getCreateTime(),"yyyy-MM-dd"));
        });
        return list.stream().map(e -> {
            ProjectAppDto dto = projectMapper.entityToAppDto(e);
            dto.setCover(ossService.getImgUrl(dto.getCover()));
            return dto;
        }).collect(Collectors.toList());
    }

    public AppApiModel newsArticle(Integer page, int size) {
        List<ProjectAppDto> list = this.getNewsArticles(page, size);
        return AppApiModel.builder().Data(list).build();
    }

    public AppApiModel getArticleByType(Integer page, Integer typeId, Integer size, Integer limitTitleLength) {
        List<ProjectDto> articles = projectService.getYangmaoListPage(page, size, typeId);
        if(limitTitleLength != null && CollUtil.isNotEmpty(articles)) {
            articles.stream().forEach(dto -> {
                if(dto.getTitle() != null && dto.getTitle().length() > limitTitleLength){
                    dto.setTitle(dto.getTitle().substring(0, limitTitleLength) + "...");
                }
            });
        }
        return AppApiModel.builder().Data(articles).build();
    }
}
